// pages/goods_detail/index.js
import { getCateGoodsDetail, getGoodsFav, getCancelFav, getAddFav, getAddCar, getCarData, resetCarCheck } from '../../api/index'
import { richImg, showToastUtil } from '../../utils/util'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsId: '',
    favStyle: false,//收藏状态-默认未收藏
    swiperList: [],
    basicInfo: {},
    properties: [],
    content: "",
    tags: ['换单包赔', '赠运费险'],
    skuNeedList: [],//处理后的双层数据
    checkList: [],//选中-全部在这一个数组中
    carNumber: 0,//购物车中商品数量
    keysList: '',//购物车商品key拼接字符
    show: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    const { goodsid } = options
    if (!this.data.show) {
      this.setData({ goodsId: goodsid, show: true }, () => {
        this.getGoodsDetail()
        this.goodsFavIf()
        this.infoCar()
      })
    }

  },
  onShow() {
    if (this.data.show) {
      this.getGoodsDetail()
      this.goodsFavIf()
      this.infoCar()
    }
  },
  // 获取商品详情
  getGoodsDetail() {
    const { goodsId } = this.data
    getCateGoodsDetail(goodsId).then(res => {
      const { pics2 = [], basicInfo = {}, properties = [], content = "", skuList = [], subPics = [] } = res.data || {}
      const swiperList = pics2.map(v => {
        return {
          id: v,
          picUrl: v
        }
      });
      const skuNeedList = this.skuListSwitch(skuList, subPics)
      // 初始选中-每一项的第一组数据
      const checkList = skuNeedList.reduce((pre, cur) => {
        pre.push(cur.children[0])
        return pre
      }, [])
      this.setData({ swiperList, basicInfo, properties, content: richImg(content), checkList, skuNeedList })
    })
  },
  // 颜色-尺码等-转换数据
  skuListSwitch(skuList = [], subPics = []) {
    let skuNeedList = skuList.reduce((pre, cur) => {
      let option = (cur.propertyChildIds.replace(/,/g, "")).split(':')
      let optionValue = (cur.propertyChildNames.replace(/,/g, "")).split(':')
      // 父级
      let optionId = Number(option[0])
      let optionName = optionValue[0]
      // 子级
      let optionValueId = Number(option[1])
      let optionValueName = optionValue[1]
      // 父级ID是否已存在，存在>-1 不存在=-1
      let ind = pre.findIndex(v => v.optionId === optionId)
      // 对应图片路径-如果有的话
      let subPicsOne = subPics.filter(v => v.optionValueId === optionValueId)

      let child = { optionId, optionName, optionValueId, optionValueName, imgUrl: subPicsOne[0] ? subPicsOne[0].pic : '' }
      if (ind > -1) {
        pre[ind].children.push(child)
      } else {
        pre.push({ optionId, optionName, children: [child] })
      }
      return pre
    }, [])
    return skuNeedList
  },
  // 商品颜色选择
  colorSelect(e) {
    const { item, parid } = e.currentTarget.dataset
    const { checkList } = this.data
    // 有初始默认值-同属性必然存在
    let checkListBef = checkList.filter(v => v.optionId !== parid)
    checkListBef.push(item)
    this.setData({ checkList: checkListBef })
  },
  // 商品是否收藏
  goodsFavIf() {
    const { goodsId } = this.data
    let favStyle = false
    getGoodsFav(goodsId).then(res => {
      if (res.code === 0) {
        // 已收藏
        favStyle = true
      }
      this.setData({ favStyle })
    })
  },
  // 取消收藏
  cancelFav() {
    const { goodsId } = this.data

    getCancelFav(goodsId).then(res => {
      if (res.code === 0) {
        showToastUtil('取消收藏成功', this.goodsFavIf)
      } else {
        showToastUtil('取消收藏失败')
      }
    })
  },
  // 添加收藏
  addFav() {
    const { goodsId, checkList } = this.data
    const params = {
      goodsId,
      extJsonStr: JSON.stringify(checkList)
    }
    getAddFav(params).then(res => {
      if (res.code === 0) {
        showToastUtil('收藏成功', this.goodsFavIf)

      } else {
        showToastUtil('收藏失败')
      }
    })
  },
  // 查询购物车
  infoCar() {
    getCarData(false).then(res => {
      const { number, items = [] } = res.data
      const keysList = items.reduce((pre, cur, index) => {
        if (index === items.length - 1) {
          pre += cur.key
        } else {
          pre += `${cur.key},`
        }
      }, '')
      this.setData({ carNumber: number, keysList })
    })
  },
  // 添加购物车
  addCar(e, type) {
    const { checkList, goodsId } = this.data
    // api工厂这个东西真不熟悉啊
    const params = {
      sku: JSON.stringify([{
        optionId: checkList[0].optionId,
        optionValueId: checkList[0].optionValueId
      }]),
      goodsId
    }
    if (!type) {
      getAddCar(params).then(res => {
        if (res.code === 0) {
          showToastUtil('添加成功', this.infoCar)
        } else {
          showToastUtil('添加失败')
        }
      })
    } else {
      getAddCar(params).then(res => {
        if (res.code === 0) {
          wx.navigateTo({
            url: '/pages/pay/index',
          });

        } else {
          showToastUtil('请求失败')
        }
      })
    }
  },
  // 立即购买
  goPay() {
    const { keysList } = this.data
    const params = {
      key: keysList || undefined,
      selected: false
    }
    resetCarCheck(params).then(res => {
      if (res.code > -1) {
        this.addCar(null, true)
      } else {
        showToastUtil('请求失败')
      }
    })
  }
})